<?php

/**
 * Application model for Cake.
 *
 * This file is application-wide model file. You can put all
 * application-wide model-related methods here.
 *
 * PHP 5
 *
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
 * Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
 * @link          http://cakephp.org CakePHP(tm) Project
 * @package       app.Model
 * @since         CakePHP(tm) v 0.2.9
 * @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
App::uses('Model', 'Model');

/**
 * Application model for Cake.
 *
 * Add your application-wide methods in the class below, your models
 * will inherit them.
 *
 * @package       app.Model
 */
class AppModel extends Model {

    private $bypass = false;

    public function getBypass() {
        return $this->bypass;
    }

    public function setBypass($bypass) {
        $this->bypass = $bypass;
    }

    public function beforeSave($options = array()) {
        foreach ($this->data as $key => $value) {
            if ($value == "NULL" || $value == "null") {
                unset($this->data[$key]);
            }
        }

        $return = false;
        if ($this->bypass) {
            $return = true;
        } else {
            App::import('Model', 'CakeSession');
            $user = CakeSession::read('user');
            //$user = $this->Session->read('user');
            $moduleId = Configure::read('moduleId');
            if (!empty($moduleId) && !empty($user['permitions']['modulesPrivileges'][$moduleId])) {
                if ($user['permitions']['modulesPrivileges'][$moduleId] == 'admin' || $user['permitions']['modulesPrivileges'][$moduleId] == 'write' ) {
                    $return = true;
                }
            }
        }
        if (!$return) {
            $log = "User has no permition to save on " . Configure::read('moduleName') . " => " . Configure::read('methodName');
            //echo $log;exit;
            $this->log($log);
        } else {
            $id = @$this->data[Configure::read('modelName')]['id'];
            $id = $this->saveAudit(empty($id)?'INSERT':'UPDATE', $this->data);
        }

        return $return;
    }

    public function beforeDelete($cascade = true) {
        $return = false;
        if ($this->bypass) {
            $return = true;
        } else {
            App::import('Model', 'CakeSession');
            $user = CakeSession::read('user');
            //$user = $this->Session->read('user');
            $moduleId = Configure::read('moduleId');
            if (!empty($moduleId) && !empty($user['permitions']['modulesPrivileges'][$moduleId])) {
                if ($user['permitions']['modulesPrivileges'][$moduleId] == 'admin' || $user['permitions']['modulesPrivileges'][$moduleId] == 'write') {
                    $return = true;
                }
            }
        }
        if (!$return) {
            $log = "User has no permition to delete on " . Configure::read('moduleName') . " => " . Configure::read('methodName');
            //echo $log;exit;
            $this->log($log);
        } else {
            $this->saveAudit('DELETE', array($this->useTable, $this->id));
        }
        return $return;
    }

    public function beforeFind($queryData) {
        if ($this->bypass)
            return true;
        App::import('Model', 'CakeSession');
        $user = CakeSession::read('user');
        //$user = $this->Session->read('user');
        $moduleId = Configure::read('currentModuleId');
        //$moduleId = Configure::read('moduleId');
        //var_dump($moduleId, Configure::read('currentModuleName'), Configure::read('moduleName') . " => " . Configure::read('methodName'),$user['permitions']['modulesPrivileges']);echo "\n\n\n<hr>\n\n\n";//exit;
        if (!empty($moduleId) && !empty($user['permitions']['modulesPrivileges'][$moduleId])) {
            if ($user['permitions']['modulesPrivileges'][$moduleId] == 'admin' || $user['permitions']['modulesPrivileges'][$moduleId] == 'write' || $user['permitions']['modulesPrivileges'][$moduleId] == 'read') {
                return true;
            }
        }
        $log = "User has no permition to find on " . Configure::read('moduleName') . " => " . Configure::read('methodName');
        //echo $log, "<br><pre>";var_dump($queryData);echo "</pre>";
        $this->log($log);
        return false;
    }

    function getLastQuery() {
        $dbo = $this->getDatasource();
        $logs = $dbo->getLog();
        $lastLog = end($logs['log']);
        return $lastLog['query'];
    }

    function saveAudit($type, $data) {
        /**
         * To do not Audit the audit save and delete get the array first item and if it is CoreAudit return 0 
         */
        if($type!='DELETE'){
            $model = "";
            foreach ($data as $key => $value) {
                $model = $key;
                break;
            }
            if($model == "CoreAudit"){
                return true;
            }
        }
        
        App::import('Model', 'CoreAudit');
        $object = new CoreAudit();
        $object->create();
        
       
        $data2 = array('CoreAudit' => array(
                'core_users_id' => Configure::read('userId'),
                'controller' => Configure::read('currentModuleName'),
                'action' => Configure::read('currentMethodName'),
                'type' => $type,
                'data' => serialize($data)
            )
        );
        
        $object->bypass = true;
        $object->save($data2);
        $object->bypass = false;
        return $object->getInsertID();
    }

}

